package com.gzpi.hwgggh.controller;

import com.gzpi.hwgggh.entity.DWTP;
import com.gzpi.hwgggh.mapper.DWTPMapper;
import com.gzpi.hwgggh.utils.HwggConstants;
import com.gzpi.hwgggh.utils.Result;
import com.sun.org.apache.xerces.internal.dom.DeferredElementImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @date : 2021-03-24 16:58
 **/
@RestController
@CrossOrigin
@RequestMapping("updateFileName")
public class UpdateFileName {

    @Autowired
    private DWTPMapper dwtpMapper;

    @RequestMapping("qwt")
    private Result updateQwtFileName(){
        try {
            /*List<DWTP> dwtps = dwtpMapper.selectDWTPList();

            for (DWTP dwtp : dwtps) {
                String qwt = dwtp.getQWT();
                if (qwt!=null){
                    String url = qwt.substring(0,qwt.lastIndexOf("/")+1);
                    String fileName = qwt.substring(qwt.lastIndexOf("/") + 1);
                    fileName = fileName.substring(0, fileName.indexOf("."));
                    dwtp.setQWT(url+fileName+".png");
                }
                dwtpMapper.updateDWTP(dwtp);
            }*/

            String filePath = "E:\\HWGGP\\";
            change(filePath);

            return Result.createSuccess("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.createError(e.toString());
        }
    }

    @RequestMapping("updateImageFileName")
    public Result updateImageFileName(){
        try {
            List<DWTP> dwtps = dwtpMapper.selectDWTPList();
            List<String> list = new ArrayList(){{
               add("16162472228998");
               add("16162471228998");
            }};
            for (DWTP dwtp : dwtps) {
                if (list.contains(dwtp.getFID())) {
                    dwtp.setQWT(newFilePath(updateImageFileName(HwggConstants.getPanFu()+dwtp.getQWT(), dwtp.getFID()).getPath()));
                    dwtp.setGHT(newFilePath(updateImageFileName(HwggConstants.getPanFu()+dwtp.getGHT(), dwtp.getFID()).getPath()));
                    dwtp.setXZT(newFilePath(updateImageFileName(HwggConstants.getPanFu()+dwtp.getXZT(), dwtp.getFID()).getPath()));
                    dwtp.setCCT(newFilePath(updateImageFileName(HwggConstants.getPanFu()+dwtp.getCCT(), dwtp.getFID()).getPath()));
                    dwtpMapper.updateDWTP(dwtp);
                    System.out.println(dwtp.getQWT());
                    System.out.println(dwtp.getGHT());
                    System.out.println(dwtp.getXZT());
                    System.out.println(dwtp.getCCT());
                }
            }
            return Result.createSuccess("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.createError(e.toString());
        }
    }

    private String newFilePath(String path){
        if (StringUtils.isNotBlank(path)){
            String pf = HwggConstants.getPanFu().substring(0,2);
            if (path.startsWith(pf)){
                return path.substring(pf.length() + 1).replace("\\","/");
            }
        }
        return null;
    }

    private File updateImageFileName(String filePath,String dwxid) throws Exception{
        File file = new File(filePath);
        if (file==null) {
            return null;
        }
        //如果是文件，修改文件名称
        String oldFileName = file.getName();
        System.out.println("原文件名 : "+oldFileName);
        //定义新的文件名称
        String newFileName = oldFileName.substring(0,oldFileName.indexOf("_")+1)+dwxid+".png";
        System.out.println("新文件名 : " + newFileName);
        //替换文件名称
        File file1 = new File(file.getParentFile() + File.separator + newFileName);
        file.renameTo(file1);
        return file1;
    }

    @RequestMapping("qjt")
    public Result updateQjtFileXml(){
        List<DWTP> dwtps = dwtpMapper.selectDWTPList();

        for (DWTP dwtp : dwtps) {
            String str ="\n\t\tset(num,\"numhs_\");\n" +
                    "\t\ttxtadd(num,get(num),get(undo_id));\n" +
                    "\t\taddhotspot(get(num));\n" +
                    "\t\thotspot[get(num)].loadstyle(numstyle1);\n" +
                    "\t\tset(hotspot[get(num)].type,\"text\");\n" +
                    "\t\tset(hotspot[get(num)].ath,0);\n" +
                    "\t\tset(hotspot[get(num)].atv,0);\n" +
                    "\t\tset(hotspot[get(num)].html,%1);\n" +
                    "\t\tset(textlen,%1);\n" +
                    "\t\tif(textlen.length == 2,set(hotspot[get(num)].width,40););\n" +
                    "\t\tif(textlen.length == 3,set(hotspot[get(num)].width,50););\n" +
                    "\t\tif(textlen.length == 4,set(hotspot[get(num)].width,60););\n" +
                    "\t\tif(textlen.length == 5,set(hotspot[get(num)].width,70););\n" +
                    "\t\tif(textlen.length == 6,set(hotspot[get(num)].width,80););\n" +
                    "\t\tif(textlen.length == 7,set(hotspot[get(num)].width,90););\n" +
                    "\t\tif(textlen.length == 8,set(hotspot[get(num)].width,100););\n" +
                    "\t\tif(textlen.length == 9,set(hotspot[get(num)].width,110););\n" +
                    "\t\tset(hotspot[get(num)].height,25);\n" +
                    "\t\tset(hotspot[get(num)].zorder,99);\n" +
                    "\t\tset(hotspot[get(num)].edge,\"center\");\n" +
                    "\n" +
                    "\t\tset(undo_array[get(undo_id)],get(num));\n" +
                    "\t\tinc(undo_id);\n";
            String path = "E:/"+dwtp.getGHQJT();
            try {
                // 创建解析器工厂
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = factory.newDocumentBuilder();
                Document document = db.parse("file:///"+path+"/tour.xml");
                //得到所有p1
                NodeList list = document.getElementsByTagName("action");
                //得到第一个p1
//            Node p1=list.item(0);
                for (int i = 0 ; i < list.getLength() ; i++){
                    Node item = list.item(i);
                    if(((DeferredElementImpl) item).getAttribute("name").equals("outputsnum")){
                        item.setTextContent(str);
                    }
                }
                // step1: 定义一个list列表，并循环赋值
                ArrayList<String> strList = new ArrayList<String>();


                // step2: 删除list列表中所有的空值
                while (strList.remove(null));
                while (strList.remove(""));

                // step3: 把list列表转换给一个新定义的中间数组，并赋值给它
                String strArrLast[] = strList.toArray(new String[strList.size()]);
//            for(int i = 0;i<strArrLast.length;i++){
//                // 向bookstore根节点中添加子节点book
//                Element name = document.createElement(strArrLast[i]);
//                Node de = document.getElementsByTagName(strArrLast[i]).item(0);
//                if(document.getElementsByTagName(strArrLast[i]).item(0) != null)//判断该该节点是否存在/存在删除
//                    p1.removeChild(de);
////                for(String key:listMap.get(i).keySet()){
////                    name.setAttribute(key, listMap.get(i).get(key));
////                }
//                p1.appendChild(name);
//            }
                // 创建TransformerFactory对象
                TransformerFactory tff = TransformerFactory.newInstance();
                // 创建 Transformer对象
                Transformer tf = tff.newTransformer();
                // 输出内容是否使用换行
                tf.setOutputProperty(OutputKeys.INDENT, "yes");
                // 创建xml文件并写入内容
                tf.transform(new DOMSource(document), new StreamResult(new File(path,"/tour.xml")));
                System.out.println(path+":修改tour.xml成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Result.createSuccess("修改成功");
    }

    private static File change(String filePath) {
        File file = new File(filePath);
        if (file == null) {
            return null;
        }
        if (file.isDirectory()) {
            //如果为目录文件，需要递归
            System.out.println("路径 : " + file.getPath());
            File []listFile = file.listFiles();
            if(listFile.length > 0){
                for (File childFile:listFile) {
                    //递归操作
                    if (childFile.getPath().contains("全景")) continue;
                    change(childFile.getPath());
                }
            }
        }else{
            //如果是文件，修改文件名称
            String oldFileName = file.getName();
            if (oldFileName.contains("QWT_")){
                System.out.println("原文件名 : "+oldFileName);
                //定义新的文件名称
                String newFileName = oldFileName.substring(0,oldFileName.indexOf("."))+".png";
                System.out.println("新文件名 : " + newFileName);
                //替换文件名称
                file.renameTo(new File(file.getParentFile()+File.separator+newFileName));
            }
        }
        return file;
    }

}
